<template>
  <van-form @submit.native.prevent="handleSubmit" class="simple-login-form">
    <van-field
      v-model="username"
      name="username"
      placeholder="用户名"
      :rules="[{ required: true, message: '请填写用户名' }]"
      class="input-field"
    />
    <van-field
      v-model="password"
      type="password"
      name="password"
      placeholder="密码"
      :rules="[{ required: true, message: '请填写密码' }]"
      class="input-field"
    />
    <van-button round block type="primary"> 提交 </van-button>
    <!-- 添加错误信息显示 -->
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </van-form>
</template>

<script>
import { Form, Field } from "vant";
import axios from "axios";

export default {
  components: {
    [Form.name]: Form, // 使用组件的 name 属性进行注册，避免潜在冲突
    [Field.name]: Field,
  },
  data() {
    return {
      username: "",
      password: "",
      errorMessage: "", // 用于显示错误信息的变量
    };
  },
  methods: {
    async handleSubmit() {
      try {
        // 发送 POST 请求到后端登录接口
        const response = await axios.post("http://127.0.0.1:8080/api/login", {
          username: this.username,
          password: this.password,
        });

        // 处理登录成功的情况
        if (response.data.success) {
          console.log("登录成功", response.data);
          // 登录成功后的操作，如路由跳转等
          this.errorMessage = ""; // 清空错误信息
        } else {
          // 处理登录失败的情况，显示后端返回的错误信息
          console.error("登录失败", response.data);
          this.errorMessage = response.data.message || "登录失败，请重试";
        }
      } catch (error) {
        // 处理请求错误的情况，显示通用的错误信息
        console.error("请求错误", error);
        this.errorMessage = "请求出错，请检查网络连接";
      }
    },
  },
  name: "LoginForm",
};
</script>

<style scoped>
.simple-login-form {
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}

.input-field {
  margin-bottom: 16px;
}

.van-button {
  margin-top: 24px;
}

/* 添加错误信息的样式 */
.error-message {
  color: red; /* 红色表示错误信息 */
  margin-top: 16px; /* 与按钮保持一定间距 */
}
</style>
